﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Demo</title>
    <!-- 请勿在项目正式环境中引用该 layui.css 地址 -->
    <link href="~/scripts/layui-v2.5.6/layui/css/layui.css" rel="stylesheet" />
</head>
<body>
    <form class="layui-form" action="">
        <div class="layui-form-item">
            <label class="layui-form-label">退料单编号</label>
            <div class="layui-input-block">
                <div class="layui-input-inline" style="width: 60%;">
                    <input type="text" id="materialReturnNo" name="materialReturnNo" lay-verify="required" placeholder="请输入退料单编号" autocomplete="off" class="layui-input">
                </div>
                <div class="layui-input-inline" style="margin-left: 10px;">
                    <input type="checkbox" id="autoGenerateSwitch" lay-skin="switch" lay-text="自动生成|手动输入" lay-filter="autoGenerateSwitch" checked>
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">退料单名称</label>
            <div class="layui-input-block">
                <input type="text" id="materialReturnName" name="materialReturnName" lay-verify="required" placeholder="请输入退料单名称" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">生产工单</label>
            <div class="layui-input-block">
                <div class="layui-input-inline" style="width: 70%;">
                    <input type="text" id="productionOrder" name="productionOrder" lay-verify="required" placeholder="请输入生产工单" autocomplete="off" class="layui-input">
                </div>
                <div class="layui-input-inline">
                    <button type="button" class="layui-btn layui-btn-normal" id="searchOrderBtn">
                        <i class="layui-icon layui-icon-search"></i>
                    </button>
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">
                接收仓库
            </label>
            <div class="layui-input-block">
                <div id="warehouseCascader" style="border: 1px solid #e6e6e6; padding: 10px; border-radius: 2px; cursor: pointer; background-color: white;">
                    <span id="warehouseDisplay" style="color: #999;">请选择</span>
                    <i class="layui-icon layui-icon-down" style="float: right; margin-top: 2px;"></i>
                </div>
                <input type="hidden" id="selectedWarehouse" name="warehouse" lay-verify="required">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">退料日期</label>
            <div class="layui-input-block">
                <input type="text" id="returnDate" name="returnDate" lay-verify="required" placeholder="yyyy-MM-dd" autocomplete="off" class="layui-input">
            </div>
        </div>
         <div class="layui-form-item">
            <label class="layui-form-label">备注</label>
            <div class="layui-input-block">
                <textarea name="remarks" placeholder="请输入内容" class="layui-textarea"></textarea>
            </div>
        </div>
        
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="formDemo">保存</button>
                <button type="button" class="layui-btn layui-btn-primary" id="cancelBtn">取消</button>
            </div>
        </div>
    </form>

    <!-- 请勿在项目正式环境中引用该 layui.js 地址 -->
    <script src="~/scripts/jquery-3.4.1.min.js"></script>
    <script src="~/scripts/layui-v2.5.6/layui/layui.js"></script>
    <script>
        layui.use(['form', 'laydate'], function(){
            var form = layui.form;
            var laydate = layui.laydate;
            
            // 日期选择器
            laydate.render({
                elem: '#returnDate',
                type: 'date',
                value: new Date()
            });
            
            // 自动生成退料单编号
            function generateMaterialReturnNo() {
                var now = new Date();
                var year = now.getFullYear();
                var month = String(now.getMonth() + 1).padStart(2, '0');
                var day = String(now.getDate()).padStart(2, '0');
                var hours = String(now.getHours()).padStart(2, '0');
                var minutes = String(now.getMinutes()).padStart(2, '0');
                var seconds = String(now.getSeconds()).padStart(2, '0');
                
                // 生成格式: TL + YYYYMMDDHHMMSS
                var materialReturnNo = 'TL' + year + month + day + hours + minutes + seconds;
                
                return materialReturnNo;
            }
            
            // 初始化时自动生成编号并设置为只读
            var generatedNo = generateMaterialReturnNo();
            $('#materialReturnNo').val(generatedNo).prop('readonly', true);
            
            // 初始化仓库级联选择
            initWarehouseCascader();
            
            // 监听开关状态变化
            form.on('switch(autoGenerateSwitch)', function(data){
                var materialReturnNoInput = $('#materialReturnNo');
                
                if(data.elem.checked) {
                    // 切换到自动生成模式
                    var newGeneratedNo = generateMaterialReturnNo();
                    materialReturnNoInput.val(newGeneratedNo).prop('readonly', true);
                    layer.msg('已切换到自动生成模式', {icon: 1, time: 1500});
                } else {
                    // 切换到手动输入模式
                    materialReturnNoInput.val('').prop('readonly', false).focus();
                    layer.msg('已切换到手动输入模式', {icon: 0, time: 1500});
                }
            });
            
            // 生产工单搜索按钮
            $('#searchOrderBtn').on('click', function() {
                showWorkOrderDialog();
            });
            
            // 显示工单选择弹窗
            function showWorkOrderDialog() {
                layer.open({
                    type: 1,
                    title: '工单选择',
                    area: ['1400px', '700px'],
                    content: buildWorkOrderDialogContent(),
                    success: function(layero, index) {
                        // 初始化弹窗内的表格和搜索功能
                        initWorkOrderDialog();
                    }
                });
            }
            
            // 构建工单选择弹窗内容
            function buildWorkOrderDialogContent() {
                return `
                    <div style="padding: 20px;">
                        <!-- 搜索条件 -->
                        <form class="layui-form" style="margin-bottom: 20px;">
                            <div class="layui-form-item">
                                <div class="layui-inline">
                                    <label class="layui-form-label" style="width: 80px;">工单编码</label>
                                    <div class="layui-input-inline" style="width: 150px;">
                                        <input type="text" id="searchWorkOrderNo" placeholder="请输入工单编码" class="layui-input">
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label" style="width: 80px;">工单名称</label>
                                    <div class="layui-input-inline" style="width: 150px;">
                                        <input type="text" id="searchWorkOrderName" placeholder="请输入工单名称" class="layui-input">
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label" style="width: 80px;">产品编号</label>
                                    <div class="layui-input-inline" style="width: 150px;">
                                        <input type="text" id="searchProductNo" placeholder="请输入产品编号" class="layui-input">
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label" style="width: 80px;">产品名称</label>
                                    <div class="layui-input-inline" style="width: 150px;">
                                        <input type="text" id="searchProductName" placeholder="请输入产品名称" class="layui-input">
                                    </div>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <div class="layui-inline">
                                    <label class="layui-form-label" style="width: 80px;">客户名称</label>
                                    <div class="layui-input-inline" style="width: 150px;">
                                        <input type="text" id="searchCustomerName" placeholder="请输入客户名称" class="layui-input">
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <button type="button" class="layui-btn" id="searchWorkOrderBtn">
                                        <i class="layui-icon layui-icon-search"></i> 搜索
                                    </button>
                                    <button type="button" class="layui-btn layui-btn-primary" id="resetSearchBtn">
                                        <i class="layui-icon layui-icon-refresh"></i> 重置
                                    </button>
                                </div>
                            </div>
                        </form>
                        
                                                 <!-- 工单列表表格 -->
                         <table class="layui-table" lay-filter="workOrderTable">
                             <thead>
                                 <tr>
                                     <th lay-data="{field:'select', width:60, align:'center'}">选择</th>
                                     <th lay-data="{field:'workOrderNo', width:140}">工单编码</th>
                                     <th lay-data="{field:'workOrderName', width:120}">工单名称</th>
                                     <th lay-data="{field:'workOrderSource', width:100}">工单来源</th>
                                     <th lay-data="{field:'orderNo', width:100}">订单编号</th>
                                     <th lay-data="{field:'productNo', width:120}">产品编号</th>
                                     <th lay-data="{field:'productName', width:120}">产品名称</th>
                                     <th lay-data="{field:'specification', width:100}">规格型号</th>
                                     <th lay-data="{field:'unit', width:80}">单位</th>
                                     <th lay-data="{field:'quantity', width:100}">工单数量</th>
                                     <th lay-data="{field:'customerNo', width:100}">客户编码</th>
                                     <th lay-data="{field:'customerName', width:100}">客户名称</th>
                                     <th lay-data="{field:'requireDate', width:120}">需求日期</th>
                                 </tr>
                             </thead>
                             <tbody id="workOrderTableBody">
                                 <!-- 数据将通过JavaScript动态加载 -->
                             </tbody>
                         </table>
                        
                        <!-- 分页 -->
                        <div id="workOrderPagination"></div>
                        
                        <!-- 按钮区域 -->
                        <div style="text-align: center; margin-top: 20px;">
                            <button type="button" class="layui-btn" id="confirmSelectBtn">确定选择</button>
                            <button type="button" class="layui-btn layui-btn-primary" id="cancelSelectBtn">取消</button>
                        </div>
                    </div>
                `;
            }
            
            // 初始化工单选择弹窗
            function initWorkOrderDialog() {
                // 全局变量存储工单数据
                var allWorkOrderData = [];
                
                // 加载工单数据
                loadWorkOrderData();
                
                // 从API加载工单数据
                function loadWorkOrderData() {
                    // 显示加载状态
                    $('#workOrderTableBody').html('<tr><td colspan="13" style="text-align: center;"><i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i> 加载中...</td></tr>');
                    
                    // 调用API获取工单数据
                    $.ajax({
                        url: '/ProductionWorkOrderMain/GetProductionWorkOrderList',
                        type: 'GET',
                        data: {
                            workOrderCode: '',
                            workOrderName: '',
                            productCode: ''
                        },
                        success: function(response) {
                            if (response && response.code === 0 && response.data) {
                                // 转换API数据格式为前端需要的格式
                                allWorkOrderData = response.data.map(function(item) {
                                    return {
                                        workOrderNo: item.workOrderCode || '',
                                        workOrderName: item.workOrderName || '',
                                        workOrderSource: item.sourceType || '',
                                        orderNo: item.orderCode || '',
                                        productNo: item.productCode || '',
                                        productName: item.productName || '',
                                        specification: item.productModel || '',
                                        unit: item.unit || '',
                                        quantity: item.workOrderQuantity || 0,
                                        customerNo: item.customerCode || '',
                                        customerName: item.customerName || '',
                                        requireDate: item.demandDate ? new Date(item.demandDate).toLocaleDateString('zh-CN') : ''
                                    };
                                });
                                renderWorkOrderTable(allWorkOrderData);
                            } else {
                                // 如果API调用失败，使用备用数据
                                loadFallbackData();
                            }
                        },
                        error: function(xhr, status, error) {
                            console.error('加载工单数据失败:', error);
                            // 如果API调用失败，使用备用数据
                            loadFallbackData();
                        }
                    });
                }
                
                // 备用数据（当API不可用时使用）
                function loadFallbackData() {
                    allWorkOrderData = [
                        {
                            workOrderNo: 'WO20250618115918',
                            workOrderName: '飞行控制系统',
                            workOrderSource: '库存备货',
                            orderNo: 'D001',
                            productNo: 'CP001',
                            productName: '飞行控制系统',
                            specification: '719*10.3',
                            unit: '吨',
                            quantity: 1500,
                            customerNo: 'KH001',
                            customerName: '李四',
                            requireDate: '2025-06-18'
                        },
                        {
                            workOrderNo: 'WO20250620695',
                            workOrderName: '电机扭矩旋转',
                            workOrderSource: '客户订单',
                            orderNo: 'D002',
                            productNo: 'CP002',
                            productName: '电机扭矩旋转',
                            specification: '800*1200',
                            unit: '吨',
                            quantity: 2000,
                            customerNo: 'KH002',
                            customerName: '张三',
                            requireDate: '2025-06-20'
                        },
                        {
                            workOrderNo: 'WO20250620610',
                            workOrderName: '摄像头机图像传输模块',
                            workOrderSource: '库存备货',
                            orderNo: 'D003',
                            productNo: 'CP003',
                            productName: '摄像头机图像传输模块',
                            specification: '120*50',
                            unit: '个',
                            quantity: 4000,
                            customerNo: 'KH003',
                            customerName: '李四',
                            requireDate: '2025-06-21'
                        },
                        {
                            workOrderNo: 'WO20250620621',
                            workOrderName: 'GPS定位模块',
                            workOrderSource: '库存备货',
                            orderNo: 'D004',
                            productNo: 'CP004',
                            productName: 'GPS定位模块',
                            specification: '300*120',
                            unit: '公斤',
                            quantity: 3500,
                            customerNo: 'KH004',
                            customerName: '赵六',
                            requireDate: '2023-06-21'
                        }
                    ];
                    renderWorkOrderTable(allWorkOrderData);
                }
                
                // 搜索按钮事件
                $('#searchWorkOrderBtn').on('click', function() {
                    var workOrderCode = $('#searchWorkOrderNo').val().trim();
                    var workOrderName = $('#searchWorkOrderName').val().trim();
                    var productCode = $('#searchProductNo').val().trim();
                    
                    // 显示加载状态
                    $('#workOrderTableBody').html('<tr><td colspan="13" style="text-align: center;"><i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i> 搜索中...</td></tr>');
                    
                    // 调用API进行搜索
                    $.ajax({
                        url: '/ProductionWorkOrderMain/GetProductionWorkOrderList',
                        type: 'GET',
                        data: {
                            workOrderCode: workOrderCode,
                            workOrderName: workOrderName,
                            productCode: productCode
                        },
                        success: function(response) {
                            if (response && response.code === 0 && response.data) {
                                // 转换API数据格式为前端需要的格式
                                var searchResults = response.data.map(function(item) {
                                    return {
                                        workOrderNo: item.workOrderCode || '',
                                        workOrderName: item.workOrderName || '',
                                        workOrderSource: item.sourceType || '',
                                        orderNo: item.orderCode || '',
                                        productNo: item.productCode || '',
                                        productName: item.productName || '',
                                        specification: item.productModel || '',
                                        unit: item.unit || '',
                                        quantity: item.workOrderQuantity || 0,
                                        customerNo: item.customerCode || '',
                                        customerName: item.customerName || '',
                                        requireDate: item.demandDate ? new Date(item.demandDate).toLocaleDateString('zh-CN') : ''
                                    };
                                });
                                
                                // 进一步过滤（客户名称等其他条件）
                                var finalResults = filterWorkOrderData(searchResults);
                                renderWorkOrderTable(finalResults);
                            } else {
                                renderWorkOrderTable([]);
                            }
                        },
                        error: function(xhr, status, error) {
                            console.error('搜索工单数据失败:', error);
                            // 回退到本地过滤
                            var filteredData = filterWorkOrderData(allWorkOrderData);
                            renderWorkOrderTable(filteredData);
                        }
                    });
                });
                
                // 重置按钮事件
                $('#resetSearchBtn').on('click', function() {
                    $('#searchWorkOrderNo').val('');
                    $('#searchWorkOrderName').val('');
                    $('#searchProductNo').val('');
                    $('#searchProductName').val('');
                    $('#searchCustomerName').val('');
                    renderWorkOrderTable(allWorkOrderData);
                });
                
                // 确定选择按钮事件
                $('#confirmSelectBtn').on('click', function() {
                    var selectedRow = $('input[name="workOrderRadio"]:checked');
                    if (selectedRow.length === 0) {
                        layer.msg('请选择一个工单', {icon: 2, time: 2000});
                        return;
                    }
                    
                    var workOrderNo = selectedRow.val();
                    
                    // 设置选中的工单编码到主表单
                    $('#productionOrder').val(workOrderNo);
                    
                    layer.closeAll();
                    layer.msg('工单选择成功', {icon: 1, time: 1500});
                });
                
                // 取消按钮事件
                $('#cancelSelectBtn').on('click', function() {
                    layer.closeAll();
                });
            }
            
            // 仓库级联选择功能
            function initWarehouseCascader() {
                // 模拟仓库数据结构
                var warehouseData = [
                    {
                        id: 'yc',
                        name: '预置仓库',
                        children: [
                            { id: 'yc_1', name: '1号仓1区', children: [] },
                            { id: 'yc_2', name: '1号仓库', children: [] }
                        ]
                    },
                    {
                        id: 'cz',
                        name: '云中港项目',
                        children: [
                            { id: 'cz_1', name: '测试仓库', children: [
                                { id: 'cz_1_1', name: '1号仓1区1位', children: [] }
                            ]}
                        ]
                    }
                ];
                
                // 点击显示仓库选择弹窗
                $('#warehouseCascader').on('click', function() {
                    showWarehouseDialog();
                });
                
                // 显示仓库选择弹窗
                function showWarehouseDialog() {
                    layer.open({
                        type: 1,
                        title: '选择仓库',
                        area: ['600px', '400px'],
                        content: buildWarehouseDialogContent(),
                        success: function(layero, index) {
                            renderWarehouseTree(warehouseData, 'level1');
                            bindWarehouseEvents();
                        }
                    });
                }
                
                // 构建仓库选择弹窗内容
                function buildWarehouseDialogContent() {
                    return `
                        <div style="padding: 20px;">
                            <div style="display: flex; height: 300px;">
                                <div style="width: 180px; border: 1px solid #e6e6e6; margin-right: 10px;">
                                    <div style="background: #f5f5f5; padding: 8px; border-bottom: 1px solid #e6e6e6; font-weight: bold;">一级仓库</div>
                                    <ul id="level1" class="warehouse-list" style="margin: 0; padding: 0; list-style: none; max-height: 260px; overflow-y: auto;">
                                        <!-- 一级仓库列表 -->
                                    </ul>
                                </div>
                                <div style="width: 180px; border: 1px solid #e6e6e6; margin-right: 10px;">
                                    <div style="background: #f5f5f5; padding: 8px; border-bottom: 1px solid #e6e6e6; font-weight: bold;">二级仓库</div>
                                    <ul id="level2" class="warehouse-list" style="margin: 0; padding: 0; list-style: none; max-height: 260px; overflow-y: auto;">
                                        <!-- 二级仓库列表 -->
                                    </ul>
                                </div>
                                <div style="width: 180px; border: 1px solid #e6e6e6;">
                                    <div style="background: #f5f5f5; padding: 8px; border-bottom: 1px solid #e6e6e6; font-weight: bold;">三级仓库</div>
                                    <ul id="level3" class="warehouse-list" style="margin: 0; padding: 0; list-style: none; max-height: 260px; overflow-y: auto;">
                                        <!-- 三级仓库列表 -->
                                    </ul>
                                </div>
                            </div>
                            
                            <div style="text-align: center; margin-top: 20px;">
                                <button type="button" class="layui-btn" id="confirmWarehouseBtn">确定选择</button>
                                <button type="button" class="layui-btn layui-btn-primary" id="cancelWarehouseBtn">取消</button>
                            </div>
                        </div>
                        
                        <style>
                            .warehouse-list li {
                                padding: 10px;
                                border-bottom: 1px solid #f0f0f0;
                                cursor: pointer;
                                transition: background-color 0.2s;
                            }
                            .warehouse-list li:hover {
                                background-color: #f8f8f8;
                            }
                            .warehouse-list li.selected {
                                background-color: #009688;
                                color: white;
                            }
                            .warehouse-list li:last-child {
                                border-bottom: none;
                            }
                        </style>
                    `;
                }
                
                // 渲染仓库树
                function renderWarehouseTree(data, targetLevel) {
                    var targetUl = $('#' + targetLevel);
                    targetUl.empty();
                    
                    if (!data || data.length === 0) {
                        return;
                    }
                    
                    data.forEach(function(item) {
                        var li = $(`
                            <li data-id="${item.id}" data-name="${item.name}" data-has-children="${item.children && item.children.length > 0}">
                                ${item.name}
                                ${item.children && item.children.length > 0 ? '<i class="layui-icon layui-icon-right" style="float: right; margin-top: 2px; color: #999;"></i>' : ''}
                            </li>
                        `);
                        targetUl.append(li);
                    });
                }
                
                // 绑定仓库选择事件
                function bindWarehouseEvents() {
                    var selectedPath = [];
                    
                    // 一级仓库点击
                    $('#level1').on('click', 'li', function() {
                        $('#level1 li').removeClass('selected');
                        $(this).addClass('selected');
                        
                        var itemId = $(this).data('id');
                        var itemName = $(this).data('name');
                        var hasChildren = $(this).data('has-children');
                        
                        selectedPath = [{ id: itemId, name: itemName }];
                        
                        // 清空右侧列表
                        $('#level2, #level3').empty();
                        
                        if (hasChildren) {
                            var selectedItem = warehouseData.find(item => item.id === itemId);
                            if (selectedItem && selectedItem.children) {
                                renderWarehouseTree(selectedItem.children, 'level2');
                            }
                        }
                    });
                    
                    // 二级仓库点击
                    $('#level2').on('click', 'li', function() {
                        $('#level2 li').removeClass('selected');
                        $(this).addClass('selected');
                        
                        var itemId = $(this).data('id');
                        var itemName = $(this).data('name');
                        var hasChildren = $(this).data('has-children');
                        
                        selectedPath[1] = { id: itemId, name: itemName };
                        selectedPath = selectedPath.slice(0, 2); // 移除三级选择
                        
                        // 清空三级列表
                        $('#level3').empty();
                        
                        if (hasChildren) {
                            // 查找二级仓库的子项
                            var level1Selected = selectedPath[0];
                            var level1Item = warehouseData.find(item => item.id === level1Selected.id);
                            if (level1Item) {
                                var level2Item = level1Item.children.find(item => item.id === itemId);
                                if (level2Item && level2Item.children) {
                                    renderWarehouseTree(level2Item.children, 'level3');
                                }
                            }
                        }
                    });
                    
                    // 三级仓库点击
                    $('#level3').on('click', 'li', function() {
                        $('#level3 li').removeClass('selected');
                        $(this).addClass('selected');
                        
                        var itemId = $(this).data('id');
                        var itemName = $(this).data('name');
                        
                        selectedPath[2] = { id: itemId, name: itemName };
                    });
                    
                    // 确定选择
                    $('#confirmWarehouseBtn').on('click', function() {
                        if (selectedPath.length === 0) {
                            layer.msg('请选择仓库', { icon: 2, time: 2000 });
                            return;
                        }
                        
                        // 构建显示文本和值
                        var displayText = selectedPath.map(item => item.name).join(' > ');
                        var value = selectedPath[selectedPath.length - 1].id;
                        
                        // 设置选中值
                        $('#warehouseDisplay').text(displayText).css('color', '#333');
                        $('#selectedWarehouse').val(value);
                        
                        layer.closeAll();
                        layer.msg('仓库选择成功', { icon: 1, time: 1500 });
                    });
                    
                    // 取消选择
                    $('#cancelWarehouseBtn').on('click', function() {
                        layer.closeAll();
                    });
                }
            }
            
            // 渲染工单表格
            function renderWorkOrderTable(data) {
                var tbody = $('#workOrderTableBody');
                tbody.empty();
                
                if (data.length === 0) {
                    tbody.append('<tr><td colspan="13" style="text-align: center;">暂无数据</td></tr>');
                    return;
                }
                
                $.each(data, function(index, item) {
                    var row = `
                        <tr>
                            <td style="text-align: center;">
                                <input type="radio" name="workOrderRadio" value="${item.workOrderNo}" data-name="${item.workOrderName}">
                            </td>
                            <td>${item.workOrderNo}</td>
                            <td>${item.workOrderName}</td>
                            <td>${item.workOrderSource}</td>
                            <td>${item.orderNo}</td>
                            <td>${item.productNo}</td>
                            <td>${item.productName}</td>
                            <td>${item.specification}</td>
                            <td>${item.unit}</td>
                            <td>${item.quantity}</td>
                            <td>${item.customerNo}</td>
                            <td>${item.customerName}</td>
                            <td>${item.requireDate}</td>
                        </tr>
                    `;
                    tbody.append(row);
                });
            }
            
            // 过滤工单数据
            function filterWorkOrderData(data) {
                var workOrderNo = $('#searchWorkOrderNo').val().trim();
                var workOrderName = $('#searchWorkOrderName').val().trim();
                var productNo = $('#searchProductNo').val().trim();
                var productName = $('#searchProductName').val().trim();
                var customerName = $('#searchCustomerName').val().trim();
                
                return data.filter(function(item) {
                    return (workOrderNo === '' || (item.workOrderNo && item.workOrderNo.indexOf(workOrderNo) !== -1)) &&
                           (workOrderName === '' || (item.workOrderName && item.workOrderName.indexOf(workOrderName) !== -1)) &&
                           (productNo === '' || (item.productNo && item.productNo.indexOf(productNo) !== -1)) &&
                           (productName === '' || (item.productName && item.productName.indexOf(productName) !== -1)) &&
                           (customerName === '' || (item.customerName && item.customerName.indexOf(customerName) !== -1));
                });
            }
            
            // 表单提交
            form.on('submit(formDemo)', function(data){
                console.log(data.field);
                
                // 验证必填字段
                if (!data.field.materialReturnNo) {
                    layer.msg('请输入退料单编号', {icon: 2, time: 2000});
                    return false;
                }
                if (!data.field.materialReturnName) {
                    layer.msg('请输入退料单名称', {icon: 2, time: 2000});
                    return false;
                }
                if (!data.field.productionOrder) {
                    layer.msg('请选择生产工单', {icon: 2, time: 2000});
                    return false;
                }
                if (!data.field.warehouse) {
                    layer.msg('请选择接收仓库', {icon: 2, time: 2000});
                    return false;
                }
                if (!data.field.returnDate) {
                    layer.msg('请选择退料日期', {icon: 2, time: 2000});
                    return false;
                }
                
                // 构建保存数据
                var saveData = {
                    returnOrderCode: data.field.materialReturnNo,
                    returnOrderName: data.field.materialReturnName,
                    productionWorkOrder: data.field.productionOrder,
                    receiveWarehouse: data.field.warehouse,
                    returnDate: data.field.returnDate + 'T00:00:00.000Z', // 转换为ISO格式
                    remark: data.field.remarks || ''
                };
                
                // 显示保存中状态
                var loadingIndex = layer.load(1, {
                    shade: [0.3, '#000']
                });
                
                // 调用API保存数据
                $.ajax({
                    url: '/ProductionMaterialReturn/SaveProductionMaterialReturn',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(saveData),
                    success: function(response) {
                        layer.close(loadingIndex);
                        if (response && response.success) {
                            layer.msg('保存成功', {icon: 1, time: 2000}, function() {
                                // 保存成功后跳转到显示页面并刷新
                                window.location.href = '/ProductionMaterialReturn/GetProductMaterReturn?t=' + new Date().getTime();
                            });
                        } else {
                            layer.msg(response.message || '保存失败', {icon: 2, time: 3000});
                        }
                    },
                    error: function(xhr, status, error) {
                        layer.close(loadingIndex);
                        console.error('保存失败:', error);
                        layer.msg('保存失败，请检查网络连接', {icon: 2, time: 3000});
                    }
                });
                
                return false; // 阻止表单默认提交
            });
            
            // 取消按钮事件
            $('#cancelBtn').on('click', function() {
                layer.confirm('确定要取消添加吗？', {icon: 3, title:'提示'}, function(index){
                    // 返回到生产退料列表页面
                    window.location.href = '/ProductionMaterialReturn/GetProductMaterReturn?t=' + new Date().getTime();
                    layer.close(index);
                });
            });
            
            // 重置表单
            function resetForm() {
                // 重新生成退料单编号（如果是自动生成模式）
                if ($('#autoGenerateSwitch').prop('checked')) {
                    var newGeneratedNo = generateMaterialReturnNo();
                    $('#materialReturnNo').val(newGeneratedNo);
                } else {
                    $('#materialReturnNo').val('');
                }
                
                // 清空其他字段
                $('#materialReturnName').val('');
                $('#productionOrder').val('');
                $('#warehouseDisplay').text('请选择').css('color', '#999');
                $('#selectedWarehouse').val('');
                $('#returnDate').val(new Date().toISOString().split('T')[0]);
                $('textarea[name="remarks"]').val('');
                
                layer.msg('表单已重置', {icon: 1, time: 1500});
            }
        });
    </script>

</body>
</html>

